package com.zhangxiaofanfan.hotcode.first;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-06-03 23:26:00
 */
public class HotCode043 {
    public static void main(String[] args) {

    }

    private final Map<TreeNode, Integer> minMap = new HashMap<>();
    private final Map<TreeNode, Integer> maxMap = new HashMap<>();

    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (root.left != null && !maxMap.containsKey(root.left) && !isValidBST(root.left)) {
            return false;
        }
        if (root.right != null && !minMap.containsKey(root.right) && !isValidBST(root.right)) {
            return false;
        }
        int maxValue = root.val, minValue = root.val;
        if (root.left != null) {
            maxValue = Math.max(maxValue, maxMap.get(root.left));
            minValue = Math.min(minValue, minMap.get(root.left));
            if (maxMap.get(root.left) >= root.val) {
                return false;
            }
        }
        if (root.right != null) {
            maxValue = Math.max(maxValue, maxMap.get(root.right));
            minValue = Math.min(minValue, minMap.get(root.right));
            if (minMap.get(root.right) <= root.val) {
                return false;
            }
        }
        maxMap.put(root, maxValue);
        minMap.put(root, minValue);
        return true;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
